package com.example.ykbboom.universitytransportation.Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.ykbboom.universitytransportation.R;
import com.example.ykbboom.universitytransportation.Util.MD5Util;
import com.example.ykbboom.universitytransportation.Util.NetUtil;
import com.example.ykbboom.universitytransportation.Util.SharedPrefUtil;
import com.example.ykbboom.universitytransportation.Util.ToastUtil;
import com.example.ykbboom.universitytransportation.VO.UserVO;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
/**
 * @author ykbboom
 * @email ykbpro@whut.edu.cn
 * @time 2017-1-27 10:28:39
 * 功能: 注册
*/
public class RegisterActivity extends BaseActivity {

    private static final int REFRESH_TIME = 1;//倒计时
    private static final int RESET_GET_VERIFY_CODE = 2;//倒计时结束可重新发送短信
    private static final int GET_VERIFY_CODE_SUCCESS = 3;//获取验证码成功
    private static final int SUBMIT_VERIFY_CODE_SUCCESS = 4;//提交验证码成功

    private Toolbar toolbar;
    private Button getVerifyCodeBtn;//获取验证码
    private EditText accountNameEdit;//输入用户名
    private EditText passwordEdit;//输入密码
    private EditText phoneNumEdit;//输入手机号
    private EditText verifyCodeEdit;//输入验证码
    private Button registerAndLoginBtn;//注册并登陆
    private static int time = 60;//显示在验证码按钮上的倒计时

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case REFRESH_TIME:
                    getVerifyCodeBtn.setText("重新发送"+"("+time+")"+"秒");
                    break;
                case RESET_GET_VERIFY_CODE:
                    getVerifyCodeBtn.setText("发送验证码");
                    getVerifyCodeBtn.setBackgroundResource(R.drawable.verify_botton);
                    getVerifyCodeBtn.setClickable(true);
                    break;
                case GET_VERIFY_CODE_SUCCESS:
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        //回调完成
                        if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                            //获取验证码成功
                            ToastUtil.showToast(RegisterActivity.this,"验证码已发送");
                        }
                    }else{
                        ((Throwable)data).printStackTrace();
                    }
                    break;
                case SUBMIT_VERIFY_CODE_SUCCESS:
                    int event1 = msg.arg1;
                    int result1 = msg.arg2;
                    if (result1 == SMSSDK.RESULT_COMPLETE) {
                        //回调完成
                        if (event1 == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                            //提交验证码成功
                            NetUtil.RegAndLogin(new UserVO(accountNameEdit.getText().toString(),
                                    phoneNumEdit.getText().toString(),
                                    MD5Util.encodeToHex(passwordEdit.getText().toString()))
                                    ,RegisterActivity.this);
                        }
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
        initSDK();
    }

    private void initSDK(){
        SMSSDK.initSDK(this,SMSSDK_APP_KEY,SMSSDK_APP_SECRET);
        EventHandler eventHandler = new EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {
                Message message = new Message();
                if (event==SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    //获取验证码成功
                    message.what = GET_VERIFY_CODE_SUCCESS;
                }else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE){
                    //提交验证码成功
                    message.what = SUBMIT_VERIFY_CODE_SUCCESS;
                }
                message.arg1 = event;
                message.arg2 = result;
                message.obj = data;
                handler.sendMessage(message);

            }
        };
        SMSSDK.registerEventHandler(eventHandler); //注册短信回调
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            //toolbar后退按钮
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @Override
    public void initView(){
        getVerifyCodeBtn = (Button) findViewById(R.id.get_verify_code_btn);
        getVerifyCodeBtn.setOnClickListener(this);
        accountNameEdit = (EditText) findViewById(R.id.account_name_edit);
        passwordEdit = (EditText) findViewById(R.id.password_edit);
        phoneNumEdit = (EditText) findViewById(R.id.phone_number_edit);
        verifyCodeEdit = (EditText) findViewById(R.id.verify_code_edit);
        registerAndLoginBtn = (Button) findViewById(R.id.register_login_btn);
        registerAndLoginBtn.setOnClickListener(this);
        toolbar = (Toolbar) findViewById(R.id.toolbar_register);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//在toolbar中显示后退
    }
    private boolean isPhoneNum(String phoneNumber){
        boolean isValid = false;
   /*
    * 可接受的电话格式有：
    */
        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";
   /*
    * 可接受的电话格式有：
    */
        String expression2 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);

        Pattern pattern2 = Pattern.compile(expression2);
        Matcher matcher2 = pattern2.matcher(inputStr);
        if(matcher.matches() || matcher2.matches()) {
            isValid = true;
        }
        return isValid;
    }
    private boolean checkUserInfo(String userName,String userPass){
        userName = accountNameEdit.getText().toString();
        userPass = passwordEdit.getText().toString();
        if (userName==null||userPass==null||userName.trim().equals("")||userPass.trim().equals("")){
            return false;
        }else
            return true;
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.get_verify_code_btn:
                if (isPhoneNum(phoneNumEdit.getText().toString())){
                    SMSSDK.getVerificationCode("86",phoneNumEdit.getText().toString());
                    getVerifyCodeBtn.setClickable(false);
                    getVerifyCodeBtn.setBackgroundResource(R.drawable.verify_btn_press);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                while(time>0){
                                    Message message = new Message();
                                    message.what = REFRESH_TIME;
                                    handler.sendMessage(message);
                                    time--;
                                    Thread.sleep(1000);
                                }
                                Message message = new Message();
                                time = 60;
                                message.what = RESET_GET_VERIFY_CODE;
                                handler.sendMessage(message);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;
                }else {
                    ToastUtil.showToast(this,"请填写正确格式的手机号");
                    break;
                }
            case R.id.register_login_btn:
                if (checkUserInfo(accountNameEdit.getText().toString(),passwordEdit.getText().toString())){
                    SMSSDK.submitVerificationCode("86",phoneNumEdit.getText().toString(),
                            verifyCodeEdit.getText().toString());
                    Message message = new Message();
                    message.what = SUBMIT_VERIFY_CODE_SUCCESS;
                    handler.sendMessage(message);
                    break;
                }else{
                    ToastUtil.showToast(this,"请完善信息");
                    break;
                }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }
}
